<template>
	<transition name="el-zoom-in-center">
		<div
			v-show="isShow"
			:style="`top: ${dropdowns.y + 5}px;left: ${dropdowns.x}px;`"
			:key="Math.random()"
			aria-hidden="true"
			class="el-dropdown__popper el-popper is-light is-pure custom-contextmenu"
			role="tooltip"
			data-popper-placement="bottom"
		>
			<ul class="el-dropdown-menu">
				<template v-if="item.type === 'line'">
					<li
						v-for="(v, k) in dropdownList"
						:key="k"
						class="el-dropdown-menu__item"
						aria-disabled="false"
						tabindex="-1"
						@click="onCurrentClick(v.contextMenuClickId)"
					>
						<i :class="v.icon" />
						<span>{{ v.txt }}{{ item.type === 'line' ? '线' : '节点' }}</span>
					</li>
				</template>
				<li v-else class="el-dropdown-menu__item" aria-disabled="false" tabindex="-1" @click="onCurrentClick(dropdownList[0].contextMenuClickId)">
					<i :class="dropdownList[0].icon" />
					<span>{{ dropdownList[0].txt }}{{ '节点' }}</span>
				</li>
			</ul>
			<div class="el-popper__arrow" style="left: 10px" />
		</div>
	</transition>
</template>

<script>
export default {
	props: {
		dropdown: {
			type: Object,
		},
	},
	data() {
		return {
			isShow: false,
			dropdownList: [
				{ contextMenuClickId: 0, txt: '删除', icon: 'el-icon-delete' },
				{ contextMenuClickId: 1, txt: '编辑', icon: 'el-icon-edit' },
			],
			item: {
				type: 'node',
			},
			conn: {},
		};
	},
	computed: {
		// 父级传过来的坐标 x,y 值
		dropdowns() {
			return this.dropdown;
		},
	},
	mounted() {
		// 监听页面监听进行右键菜单的关闭
		document.body.addEventListener('click', this.closeContextmenu);
		document.body.addEventListener('contextmenu', this.closeContextmenu);
	},
	// 页面卸载时，移除右键菜单监听事件
	unmounted() {
		document.body.removeEventListener('click', this.closeContextmenu);
		document.body.removeEventListener('contextmenu', this.closeContextmenu);
	},
	methods: {
		// 当前项菜单点击
		onCurrentClick(contextMenuClickId) {
			this.$emit('current', Object.assign({}, { contextMenuClickId }, this.item), this.conn);
		},
		// 打开右键菜单：判断是否固定，固定则不显示关闭按钮
		openContextmenu(item, conn) {
			this.item = item;
			this.conn = conn;
			this.closeContextmenu();
			setTimeout(() => {
				this.isShow = true;
			}, 10);
		},
		// 关闭右键菜单
		closeContextmenu() {
			this.isShow = false;
		},
	},
};
</script>

<style scoped lang="scss">
.custom-contextmenu {
	transform-origin: center top;
	z-index: 2190;
	position: fixed;
	.el-dropdown-menu__item {
		font-size: 12px !important;
		white-space: nowrap;
		i {
			font-size: 12px !important;
		}
	}
}
</style>
